package org.road0329.dlt698.axdr;

import org.road0329.dlt698.ReverseByteArrayInputStream;
import org.road0329.dlt698.ReverseByteArrayOutputStream;
import org.road0329.dlt698.asn1.axdr.AxdrEnum;
import org.road0329.dlt698.asn1.axdr.AxdrType;

import java.io.IOException;

public class Region extends AxdrType {
    private byte[] dataCode = null;
    private AxdrEnum unit = null;
    private Data sval = null;
    private Data eval = null;

    public Region() {
    }

    public byte[] getDataCode() {
        return dataCode;
    }

    public AxdrEnum getUnit() {
        return unit;
    }

    public Data getSval() {
        return sval;
    }

    public Data getEval() {
        return eval;
    }

    public void setDataCode(byte[] dataCode) {
        this.dataCode = dataCode;
    }

    public void setAll(AxdrEnum unit, Data sval, Data eval) {
        this.unit = unit;
        this.sval = sval;
        this.eval = eval;
    }

    @Override
    public int decode(ReverseByteArrayInputStream input) throws Exception {
        int codeLength = 0;
        this.unit = new AxdrEnum();
        this.unit.setConst();
        codeLength += this.unit.decode(input);
        this.sval = new Data();
        codeLength += this.sval.decode(input);
        this.eval = new Data();
        codeLength += this.eval.decode(input);
        return codeLength;
    }

    @Override
    public int encode(ReverseByteArrayOutputStream output) throws Exception {
        int codeLength;
        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (int i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if (this.unit != null && this.eval != null && this.sval != null) {
                codeLength = 0;
                codeLength += this.eval.encode(output);
                codeLength += this.sval.encode(output);
                codeLength += this.unit.encode(output);
            } else {
                throw new Exception("unit or sval or eval is null");
            }
        }
        return codeLength;
    }

    public void encodeAndSave(int encodingSizeGuess) throws Exception {
        ReverseByteArrayOutputStream revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.toByteArray();
    }

    @Override
    public String toString() {
        if (this.unit != null && this.sval != null && this.eval != null) {
            return "sequence: {" + "unit: " + this.unit + ", sval: " + this.sval + ", eval: " + this.eval + "}";
        } else {
            return "unit or sval or eval is null";
        }
    }
}



